'''
Created on Dec 5, 2010

@author: jackreilly
'''
from google.appengine.ext import db
from jettube.models import getFromJetKey, User
from jettube.server.utilities import dateString

NCOMMENTS = 20
SONG_ID_KEY = 'songid'
COMMENT_KEY = 'comment'
KEY_KEY = 'commentKey'
POSTER_KEY = 'poster'
DATE_KEY = 'commentDate'



class Comment( db.Model ):
    date = db.DateTimeProperty( auto_now_add = True )
    comment = db.StringProperty()
    songid = db.StringProperty()
    user = db.ReferenceProperty( User.User )

def getCommentsDictionaryFromSongId(songid):
    return getCommentsDictionaryFromComments(commentsFromSongId(songid))

def commentsFromSongId(songid):
    return Comment.all().filter('songid',songid).order('-date').fetch(NCOMMENTS)

def commentsFromRequest(request):
    songid = getFromJetKey(request, SONG_ID_KEY)
    return commentsFromSongId(songid)

def putNewCommentFromRequest(request):
    comment = getFromJetKey(request, COMMENT_KEY)
    songid = getFromJetKey(request, SONG_ID_KEY)
    user = User.getUserFromRequest(request)
    if not comment or not songid:
        return False
    try:
        newComment = Comment(key_name = generateKeyFromSongIdUser(songid, user))
        newComment.songid = songid
        newComment.user = user
        newComment.comment = comment
        newComment.put()
    except:
        return False
        
def generateKeyFromSongIdUser(id,user):
    return '%s ::: %s' % (id, user.key())

def getCommentsDictionaryFromComments(comments):
    return [{KEY_KEY:str(comment.key()), 
             COMMENT_KEY:comment.comment, 
             User.PIC_KEY:comment.user.picUrl,
             POSTER_KEY:comment.user.name,
             DATE_KEY:dateString(comment.date)} for comment in comments]
    
def getCommentsDictionaryFromRequest(request):
    comments = commentsFromRequest(request)
    return getCommentsDictionaryFromComments(comments)
    